package com.yyfax.pay.common.util;

import java.net.InetAddress;
import java.net.UnknownHostException;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * request工具类
 * 
 * @author buyi
 * @date 2017-05-11 14:36:59
 * @since v1.0.0
 */
public class RequestUtil {
	private static Logger logger = LoggerFactory.getLogger(RequestUtil.class);

	/**
	 * 获取真实Ip
	 * 
	 * @author buyi
	 * @date 2017-05-11 14:37:11
	 * @since v1.0.0
	 * @return
	 */
	public static String getIpAdr(HttpServletRequest request) {
		if (request == null) {
			logger.warn("获取真实ip地址，请求参数request为空");
			return null;
		}

		String ip = request.getHeader("X-Forwarded-For");
		if (StringUtils.isBlank(ip) || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("x-for");
		}
		if (StringUtils.isBlank(ip) || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("Proxy-Client-IP");
		}
		if (StringUtils.isBlank(ip) || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("WL-Proxy-Client-IP");
		}
		if (StringUtils.isBlank(ip) || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getRemoteAddr();
		}

		if ("0:0:0:0:0:0:0:1".equals(ip) || "127.0.0.1".equals(ip)) {
			InetAddress inetAddress = null;
			try {
				inetAddress = InetAddress.getLocalHost();
				ip = inetAddress.getHostAddress();
			} catch (UnknownHostException e) {
				logger.error("获取请求IP地址异常",e);
			}

		}

		if (ip != null && ip.length() > 15) {
			if (ip.indexOf(",") > 0) {
				ip = ip.substring(0, ip.indexOf(","));
			}
		}

		return ip;
	}
}
